﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using Zo.Json;

namespace Zo.Http
{
    /// <summary>
    /// HTTP 处理器。
    /// </summary>
    public class HttpProcessor
    {
        /// <summary>
        /// 基本的 HTTP POST 数据。
        /// </summary>
        /// <param name="url">提交地址。</param>
        /// <param name="parameters">提交数据。</param>
        /// <param name="headers"></param>
        /// <returns>结果。</returns>
        public static string HttpPost(string url, IDictionary<string, string> parameters, IDictionary<string, string> headers = null)
        {
            var postData = string.Empty;

            if (parameters != null && parameters.Count > 0)
            {
                foreach (var parameter in parameters)
                {
                    if (!string.IsNullOrWhiteSpace(postData))
                    {
                        postData += "&";
                    }

                    var value = HttpUtility.UrlEncode(parameter.Value);

                    postData += $"{parameter.Key}={value}";
                }
            }

            var result = HttpPost(url, postData, headers, null, "application/x-www-form-urlencoded", Encoding.UTF8);

            return result;
        }

        /// <summary>
        /// HTTP POST JSON 数据。
        /// </summary>
        /// <param name="url">提交地址。</param>
        /// <param name="jsonData">JSON 数据。</param>
        /// <param name="headers"></param>
        /// <returns>结果。</returns>
        public static string HttpJsonPostData(string url, string jsonData, IDictionary<string, string> headers = null)
        {
            var data = jsonData ?? string.Empty;

            var result = HttpPost(url, data, headers, null, "application/json", Encoding.UTF8);

            return result;
        }

        /// <summary>
        /// HTTP POST JSON 数据。
        /// </summary>
        /// <param name="url">提交地址。</param>
        /// <param name="model">数据对象模型。</param>
        /// <returns>结果。</returns>
        public static string HttpJsonPostData(string url, object model, IDictionary<string, string> headers = null)
        {
            var data = JsonManager.Serialize(model);

            var result = HttpPost(url, data ?? string.Empty, headers, null, "application/json", Encoding.UTF8);

            return result;
        }

        #region http post

        public static string HttpPost(string url, string postData, IDictionary<string, string> headers, string userAgent, string contentType, Encoding encoding)
        {
            var strHtmlContent = "";
            HttpWebRequest request;
            try
            {
                //声明一个HttpWebRequest请求
                request = (HttpWebRequest)WebRequest.Create(url);
                //连接超时时间
                request.Timeout = 20000;

                if (headers != null && headers.Count > 0)
                {
                    foreach (var header in headers)
                    {
                        request.Headers.Set(header.Key, header.Value);
                    }
                }

                request.UserAgent = userAgent ?? string.Empty;
                request.KeepAlive = true;
                request.Proxy = null;

                var data = encoding.GetBytes(postData);

                request.Method = "POST";
                request.ContentType = contentType ?? string.Empty;
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                var response = (HttpWebResponse)request.GetResponse();
                var streamHtmlCode = response.GetResponseStream();
                if (streamHtmlCode != null)
                {
                    //var encoding = Encoding.GetEncoding("utf-8");
                    var streamReader = new StreamReader(streamHtmlCode, encoding);
                    strHtmlContent = streamReader.ReadToEnd();

                    streamReader.Close();
                    streamHtmlCode.Close();
                }
                else
                {
                    strHtmlContent = "请求错误：response.GetResponseStream() 返回的数据是 Null";
                }

                response.Close();
                request.Abort();

                response = null;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                request = null;
            }

            return strHtmlContent ?? string.Empty;
        }

        #endregion http post
    }
}